package com.xcdh.test.controller;

import com.xcdh.test.util.I18nEnum;
import com.xcdh.test.util.I18nResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@RestController
public class i18nTestController {

    @Autowired
    private LocaleResolver localeResolver;

    @Autowired
    private MessageSource messageSource;

    @GetMapping("/test/i18n")
    public I18nResponse TestI18n(HttpServletRequest request, HttpServletResponse response,
                                 @RequestHeader(value = "language",required = false) String language) {

        // 假如这是一个拦截器，拿到了语言就可以设置使用哪种语言
        Locale locale = null;

        // 根据传入值的不同设置不同的语言
        if (language!=null&&language.equals("en")) locale = new Locale("en", "US");
        if (language!=null&& language.equals("zh")) locale = new Locale("zh", "CN");
        if (locale!=null)localeResolver.setLocale(request, response, locale);

        // 这里是就是执行完逻辑给前端的提示
        return new I18nResponse("0001", I18nEnum.USER_NAME_ISNOT_NULL);
    }



    @GetMapping("/greeting")
    @ResponseBody
    public String getGreeting(@RequestHeader(value = "language",required = false) String language) {
        Locale locale = new Locale(language);
        return messageSource.getMessage("greeting", null, locale);
    }
}
